// components/select-checkbox/select-checkbox.ts
Component({
    /**
     * 组件的属性列表
     */
    properties: {
      place: String, // 输入框提示
      list: Array, // 选择器 选项
      checkSelected: { // 选择器 选项数组中 对象的value的默认key
        type: String,
        value: ''
      }
    },
    // 监听传入的变量,当传入的值发生变化时,触发方法
    observers: {
      'checkSelected': function (val) {
        console.log('接收到checkSelected:', val);
        
        if (!val) {
          this.setData({
            result: [],
            displayValue: ''
          });
          return;
        }
        
        // 分割字符串并过滤空值
        const selectedValues = val.split(',').filter(item => item && item.trim() !== '');
        console.log('原始选中值:', selectedValues);
        
        // 使用父组件传进来的值匹配选项的name
        const matchedResults = this.matchSelectedValues(selectedValues, this.properties.list);
        console.log('匹配后的结果:', matchedResults);
        
        this.setData({
          result: matchedResults,
          displayValue: matchedResults.join(',')
        });
      }
    },
    /**
     * 页面的初始数据
     */
    data: {
      icon:'arrow-down',  // 下拉箭头
      show: false,
      result: [],
      displayValue: '', // 添加显示值
    },
    /**
     * 组件的方法列表
     */
    methods: {
      // 添加匹配方法：用传入的值匹配选项name
      matchSelectedValues(selectedValues: string[], optionList: string[]): string[] {
        if (!selectedValues || !optionList) return [];
        
        const matched: string[] = [];
        
        selectedValues.forEach(selectedValue => {
          // 精确匹配
          const exactMatch = optionList.find(option => option === selectedValue);
          if (exactMatch) {
            matched.push(exactMatch);
            return;
          }
          
          // 模糊匹配：忽略空格和大小写
          const normalizedSelected = selectedValue.replace(/\s+/g, '').toLowerCase();
          const fuzzyMatch = optionList.find(option => 
            option.replace(/\s+/g, '').toLowerCase() === normalizedSelected
          );
          if (fuzzyMatch) {
            matched.push(fuzzyMatch);
            return;
          }
          
          // 包含匹配
          const containsMatch = optionList.find(option => 
            option.includes(selectedValue) || selectedValue.includes(option)
          );
          if (containsMatch) {
            matched.push(containsMatch);
          }
        });
        
        return matched;
      },
      
      // 取消
      cancel() {
        this.setData({ 
          show: false,
          // 取消时恢复到原始选中状态
          result: this.data.displayValue ? this.data.displayValue.split(',').filter(item => item) : []
        });
      },
      
      // 确定
      confirm() {
        const selectedValue = this.data.result.join(',');
        console.log('确认选择:', selectedValue);
        
        this.setData({ 
          show: false,
          displayValue: selectedValue
        });
        
        this.triggerEvent('sync', {
          value: selectedValue
        });
      },
  
      showPopup() {
        console.log('打开弹出层，当前选中:', this.data.result);
        console.log('选项列表:', this.properties.list);
        this.setData({ 
          show: true,
          // 确保打开时使用匹配后的结果
          result: this.data.displayValue ? 
            this.data.displayValue.split(',').filter(item => item) : []
        });
      },
      
      onClose() {
        this.setData({ 
          show: false,
          // 关闭时恢复到显示值状态
          result: this.data.displayValue ? this.data.displayValue.split(',').filter(item => item) : []
        });
      },
      
      onChange(event) {
        console.log('复选框变化:', event.detail);
        const detail = event.detail.filter((r) => r !== '' && r !== undefined && r !== null);
        this.setData({
          result: detail
        });
        // 注意：这里不再设置 checkSelected，因为它是父组件传入的属性
      },
      
      toggle(event) {
        const { index } = event.currentTarget.dataset;
        const checkbox = this.selectComponent(`.checkboxes-${index}`);
        if (checkbox) {
          checkbox.toggle();
        }
      },
      
      noop() {},
    },
    
    lifetimes: {
      attached() {
        console.log("父组件传过来:", this.properties.checkSelected);
        console.log("选项列表:", this.properties.list);
        
        // 初始化时进行匹配
        if (this.properties.checkSelected) {
          const selectedValues = this.properties.checkSelected.split(',').filter(item => item);
          const matchedResults = this.matchSelectedValues(selectedValues, this.properties.list);
          
          this.setData({
            result: matchedResults,
            displayValue: matchedResults.join(',')
          });
        }
      }
    },
  });